#!/bin/ash -efu
#
# mki-build-propagator
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_BUILD_PROPAGATOR:-}"
mar_modules="${PROPAGATOR_MAR_MODULES:?Mar morules required}"
initfs="${PROPAGATOR_INITFS:?initfs required}"

[ -d "$chroot" ] ||
	fatal "$dir: does not look like a hasher work directory."

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

cp -pLft "$chroot/.in/" -- "$mar_modules" "$initfs"

make_exec "$chroot/.host/packimage.sh" <<EOF
#!/bin/sh -efu${verbose:+x}

libdir="\$(getconf LIBDIR)"

case "`arch`" in
	e2k)
		kname=image
		;;
	*)
		kname=vmlinuz
		;;
esac

if [ -L /boot/\$kname ]; then
	kimage="\$(readlink -mv /boot/\$kname)"
else
	kimage="\$(find /boot -type f -name "\$kname-*" -print -quit)"
fi
kver="\${kimage#/boot/\$kname-}"

mkmodpack -p '/.in/${mar_modules##*/}' -o /tmp/modules -k "\$kver"

printf '%s\n' "${PROPAGATOR_VERSION:-}" > /tmp/.VERSION

rm -f /boot/full.cz

[ ! -f /tmp/modules ] ||
	cat "\$libdir/propagator/initfs" /tmp/modules > /boot/full.cz

sed \
	-e "s,@LIBDIR@,\$libdir," \
	-e "s,@TMPDIR@,/tmp,g" \
	< '/.in/${initfs##*/}' |
	gencpio - |
	gzip -c >> /boot/full.cz

rm -rf -- /tmp/.VERSION
EOF

rc=0
mki-run "/.host/packimage.sh" || rc=$?
rm -f -- "$chroot/.host/packimage.sh"
find "$chroot/.in" -mindepth 1 -maxdepth 1 -exec rm -rf -- '{}' '+'
exit $rc
